package com.book.common.api.helper;

import com.book.common.result.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * Description：
 * @Author： leo.xiong
 * @CreateDate： 2020/04/20 16:36
 * @Email： leo.xiong@suyun360.com
 * Version：1.0
 */
public class TransformHelper {


    /**
     * 转换普通对象
     *
     * @param obj
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T transform(Object obj, Class<T> clazz) {
        try {
            T t = clazz.newInstance();
            if (Objects.isNull(obj)) {
                return t;
            }
            BeanUtils.copyProperties(obj, t);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 转换List对象
     *
     * @param objectList
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> transformList(List objectList, Class<T> clazz) {
        List<T> tList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(objectList)) {
            return tList;
        }
        return Lists.transform(objectList, loginLog -> {
            return transform(loginLog, clazz);
        });
    }

    public static <T, E> PageInfo<T> transformPage(PageInfo entityPageInfo, Class<T> clazz) {
        PageInfo<T> pageInfo = new PageInfo<>(entityPageInfo.getPageNo(), entityPageInfo.getPageSize(), entityPageInfo.getCount());
        pageInfo.setList(transformList(entityPageInfo.getList(), clazz));
        return pageInfo;
    }
}
